package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.New;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.dialog.LoadingDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;

public class NewDetailActivity extends Activity {

	/**
	 * 标题
	 */
	private TextView tvTitle = null;

	private ViewGroup btnBack = null;

	private ViewGroup btnMeanMore = null;

	private WebView wvNewsDetail = null;

	private int position = 0;

	private String newsId = null;

	private User user = null;

	public static final int TO_COMMENT = 1;

	LoadingDialog dia;

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.newdetail);

		user = (User) getIntent().getSerializableExtra("user");

		position = getIntent().getIntExtra("position", 0);

		tvTitle = (TextView) findViewById(R.id.tvTitle);

		btnBack = (ViewGroup) findViewById(R.id.btnBack);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				doBack();
			}
		});

		View view = GoHomeUtil.createPopView(NewDetailActivity.this,
				new String[] { "刷新", "评论", "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btnRefresh = (Button) pop.getContentView()
				.findViewWithTag("btn0");

		final Button btnPingLun = (Button) pop.getContentView()
				.findViewWithTag("btn1");

		final Button btnGoHome = (Button) pop.getContentView().findViewWithTag(
				"btn2");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				}

				if (v == btnRefresh) {
					dia.dismiss();
					// blpProgress.startLoading();
					//
					// blpProgress.setVisibility(View.VISIBLE);

					wvNewsDetail.reload();

				} else if (v == btnPingLun) {

					Intent to_news_comment = new Intent(NewDetailActivity.this,
							NewsCommentActivity.class);

					to_news_comment.putExtra("user", user);

					to_news_comment.putExtra("id", newsId);

					startActivityForResult(to_news_comment, TO_COMMENT);

				} else if (v == btnGoHome) {

					GoHomeUtil.goHome(NewDetailActivity.this);

				}

			}
		};

		btnRefresh.setOnClickListener(menuOnClick);

		btnPingLun.setOnClickListener(menuOnClick);

		btnGoHome.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

		String title = getIntent().getStringExtra("title");
		tvTitle.setText(title);

		newsId = getIntent().getStringExtra("id");

		New newObj = (New) getIntent().getSerializableExtra("new");

		wvNewsDetail = (WebView) findViewById(R.id.wvNewsDetail);

		// 自动加载图片
		wvNewsDetail.getSettings().setLoadsImagesAutomatically(true);
		wvNewsDetail.getSettings().setJavaScriptEnabled(true);

		wvNewsDetail.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {

				// blpProgress.stopLoading();
				//
				// blpProgress.setVisibility(View.GONE);
				dia.dismiss();

				if (wvNewsDetail.getTag() != null
						&& (Boolean) wvNewsDetail.getTag()) {

					float webViewContentHeight = wvNewsDetail
							.getContentHeight() * wvNewsDetail.getScale();

					wvNewsDetail.scrollTo(0, (int) webViewContentHeight);

					wvNewsDetail.setTag(null);

				}

			}
		});

		String url = new ConfigUtil(getResources()).getPreHttpUrl()
				+ getString(R.string.new_detail) + newObj.getId();

		User user = (User) getIntent().getSerializableExtra("user");

		if (user != null && CharsetUtil.isNotNull(user.getUsername())) {
			url += "/username/" + user.getUsername();
		}
		dia = new LoadingDialog(NewDetailActivity.this);
		dia.setCanceledOnTouchOutside(false);
		//		dia.setOnKeyListener(keylistener);
		dia.show();
		wvNewsDetail.loadUrl(url);
	}

	OnKeyListener keylistener = new DialogInterface.OnKeyListener(){
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	} ;


	@Override
	public void onBackPressed() {
		doBack();
	}

	/**
	 * 处理返回的结果
	 */
	private void doBack() {
		Intent intent = new Intent();

		intent.putExtra("position", position);

		setResult(NewListItemFragment.FORWORD_DETAIL_REQUEST_CODE, intent);

		finish();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == TO_COMMENT) {//刷新

			if (wvNewsDetail != null) {

				wvNewsDetail.setTag(true);

				dia.show();

				wvNewsDetail.reload();

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

}
